var stats = new Stats();
var c = document.getElementById('c'),
    myCtx = c.getContext('2d'),
    fps;

window.addEventListener('resize', handleWindowResize, false);
function handleWindowResize() {
    c.width = window.innerWidth * window.devicePixelRatio;
    c.height = window.innerHeight * window.devicePixelRatio;
}
handleWindowResize();

/* 自定义用户策略 */
function drawSprite (sprite,  ctx) {
    var painter = sprite.painter;
    sprite.width = painter.image.width;
    sprite.height = painter.image.height;
    ctx.save();
    sprite.top = 100;
    sprite.left = 300;
    ctx.drawImage(painter.image, sprite.left, sprite.top, sprite.width, sprite.height);
    sprite.top = 400;
    sprite.left = 500;
    ctx.drawImage(painter.image, sprite.left, sprite.top, sprite.width, sprite.height);
    sprite.top = 800;
    sprite.left = 1000;
    ctx.drawImage(painter.image, sprite.left, sprite.top, sprite.width, sprite.height);
    /* 以上代码对享元模式进行了体现 */
    ctx.restore();
}
function drawSpriteSheet(sprite, ctx) {
    var painter = sprite.painter,
        cell = painter.cells[painter.cellIndex];
    ctx.save();
    sprite.width = painter.spriteSheet.width;
    sprite.height = painter.spriteSheet.height;
    ctx.drawImage(painter.spriteSheet, cell.x, cell.y, cell.w, cell.h, sprite.left, sprite.top, sprite.width, sprite.height);
    ctx.restore();
}
function b_runInPlace(sprite, behavior, ctx, now) {
    //控制变化速率，记录两次advance之间的时差，从而控制变化的间隔
    if(now - behavior.lastAdvance > behavior.PAGEFLIP_INTERVAL) {
        sprite.painter.advance();
        behavior.lastAdvance = now;
    }
}
function b_leftToRight(sprite, behavior, ctx, now) {
    if(!now) now = 0;
    if(behavior.lastMove !== 0) {
        sprite.vX = 100; //此处速度为每秒位移的像素数
        sprite.left += sprite.vX * ((now - behavior.lastMove) / 1000);
        // sprite.left += sprite.vX;
        if(sprite.left + sprite.width > c.width) {
            sprite.left = 0;
        }
    }
    behavior.lastMove = now;
}


var sprite = new Sprite('test');
var curPainter = sprite.setPainter({
    spriteSheetUrl: '../../images/test.jpg', //实际开发中一般要求带域名的完整url
    cells: [{ x: 0, y: 112, w: 56, h: 56 }, { x: 56, y: 112, w: 56, h: 56 }, { x: 112, y: 112, w: 56, h: 56 }, { x: 168, y: 112, w: 56, h: 56}],
    action: drawSpriteSheet
});
sprite.addBehavior(b_runInPlace, {
    lastAdvance: 0,
    PAGEFLIP_INTERVAL: 100
});
sprite.addBehavior(b_leftToRight, {
    lastMove: 0
});

(function loop(time) {
    myCtx.clearRect(0, 0, c.width, c.height);
    sprite.paint(myCtx);
    sprite.update(myCtx, time);

    // var tempFps = stats.update();
    // fps = tempFps === 0 ? 60 : tempFps;
    requestAnimationFrame(loop);
}());